package com.xxx.system.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    //进入cotroller之前检查token
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userType = request.getHeader("userType");
        if (!StrUtil.isBlank(userType)) {
            return true;
        }
        String token = request.getHeader("token");
        //获取token的信息
        if (token != null) {
            try {
                Payload payload = JwtUtil.parseJwtToken(token);
                return true;//放行
            } catch (Exception e) {
                e.printStackTrace();
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
                return false;
            }
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
        return false;
    }
}
